package com.bawei.module_publish.openlive.ui

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.module_publish.databinding.DialogSendAdvertisementBinding
import com.bawei.module_publish.openlive.adapter.AdItem
import com.bawei.module_publish.openlive.adapter.AdSelectAdapter
import com.bawei.module_publish.openlive.intent.LiveIntent
import com.bawei.module_publish.openlive.model.entity.SendAdInfoBody
import com.bawei.module_publish.openlive.state.LiveState
import com.bawei.module_publish.openlive.viewmodel.LiveViewModel
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch
private const val TAG = "LiveAdDialog"
class LiveAdDialog : BottomSheetDialogFragment() {

    private var _binding: DialogSendAdvertisementBinding? = null
    private val binding get() = _binding!!

    private var selectedAd: AdItem? = null
    private var onAdSent: ((AdItem) -> Unit)? = null

    private lateinit var liveViewModel: LiveViewModel

    // 模拟广告数据
    private val adList = listOf(
        AdItem(1, "限时优惠！全场商品8折起，快来抢购吧！", "https://ts1.tc.mm.bing.net/th/id/OIP-C.KYvvEgGF4e3IbXNeZpL6KgAAAA?w=258&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2"),
        AdItem(2, "新品上市！独家定制款，仅此一家！", "https://tse4-mm.cn.bing.net/th/id/OIP-C.0nmFhW1REQaavad_no8rbgHaEJ?w=322&h=181&c=7&r=0&o=5&dpr=1.5&pid=1.7"),
        AdItem(3, "会员专享！充值送好礼，福利多多！", "https://tse3-mm.cn.bing.net/th/id/OIP-C.kdjoNA7PW3Ges7nv-O6c7gHaJ4?w=137&h=183&c=7&r=0&o=5&dpr=1.5&pid=1.7"),
        AdItem(4, "直播专享价！比双11更便宜！", "https://tse3-mm.cn.bing.net/th/id/OIP-C.MBa8TZj_5mkq_wY7KWYyLAHaLG?w=128&h=191&c=7&r=0&o=5&dpr=1.5&pid=1.7")
    )
    override fun onStart() {
        super.onStart()
        dialog?.let {
            val bottomSheet = it.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            bottomSheet?.layoutParams?.height = (resources.displayMetrics.heightPixels * 0.85).toInt()
            bottomSheet?.requestLayout()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogSendAdvertisementBinding.inflate(inflater, container, false)
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initRecyclerView()
        initClickListeners()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._addAdFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.AdInfoSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            dismiss()
                            ToastUtils.showLong("发布圈钱广告成功")
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }

    private fun initRecyclerView() {
        val adapter = AdSelectAdapter(adList) { ad ->
            selectedAd = ad
        }
        
        binding.rvAdList.apply {
            layoutManager = LinearLayoutManager(context)
            this.adapter = adapter
        }
    }

    private fun initClickListeners() {
        binding.btnSend.setOnClickListener {
            val ad = selectedAd
            if (ad != null) {
                onAdSent?.invoke(ad)
                val sendAdInfoBody = SendAdInfoBody(
                    ad.desc,
                    "285417033236483",
                    ad.imgUrl
                )
                lifecycleScope.launch {
                    liveViewModel.intents.send(LiveIntent.AdInfo(sendAdInfoBody))
                }
            } else {
                Toast.makeText(context, "请先选择一个广告", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun setOnAdSentListener(listener: (AdItem) -> Unit) {
        onAdSent = listener
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 